<?php
function current_page_name(){
	return trim(end (explode ( "/" , $_SERVER["SCRIPT_NAME"] ) ) );
}

function is_current($pagename){
	$current_page_name = current_page_name();
	if ( strcmp($pagename, $current_page_name ) == 0 )
		echo "class='current'";
	
}


/* Funzione per stampare i box contenenti i libri (nella homepage ad esempio)
 * $category_id viene passato per stampare i libri di una categoria specifica
 */

function print_books($subject, $sortby, $page ,$random){
	global $db;
	$books = $db->get_all_books($subject, $sortby, $page, $random);
	//echo "<div id='searching'></div>";
	if (isset( $_GET['subject'])){
		print_pagination($_GET['subject'], (isset($_GET['page'] ) ) ? $_GET['page']: 1 , $books['num_pages']);
		echo "<div id='page-description'><h5 style='margin-left:10px;'>Materia: <b>".$_GET['subject']."</b></h5></div>";
		
	}
	else echo "	<div id='page-description'></div>";
	
	echo "<div id='frontpage'>";
	if ( $books['list'] ){
		$i = 0;
		foreach ($books['list'] as $book):
		
		?>
		<!--Shop item-->   
		
			<div class="shop-item <?php	$i++; if (false) { echo "column-last"; $i = 0;} ?>">
				<!--Ribbon-->
				<!-- <span class="out-of-stock"></span>  -->
		        
				<div class="boxgrid slidedown">
				<div class="newly_added_product"><p>Prodotto aggiunto</p></div>
				<h5><?=$book['title']?></h5>
				<div class="covers"/><img  src="<?php the_cover($book['id'], $book['EAN'])?>"></div>  
				<div class="box-info-container">
				<p class="box_label">Autore</p><p> <?=$book['author']?></p>
				<p class="box_label">Editore</p><p> <?=$book['publisher']?></p>
				</div>
				</div>
				<!--Item price and button-->        
				<div class="boxgrid-info-box">
							<a id="show_num_copies_<?=$book['id']?>" onclick="show_num_copies(this.id)" class="button white-button add">Aggiungi al tuo elenco</a>
								
					<div>
						<input type="hidden" id="num_copies">
						<div class="slide_down_container">
							 <div class="slide_down_copies">
									<label for="num_copies_input">Numero copie</label>						 	
							 		<input id="num_copies_input" class="positive-integer" type="text"  value="1" size="5px" maxlength="3">
							 		<input type="button" value="Aggiungi" id="send_num_copies_<?=$book['id']?>" onclick="send_book_request(this.id)">
							 		<input style="float:right;" id="cancel_num_copies_<?=$book['id']?>" type="button" onclick="hide_num_copies(this.id)" value="Annulla">
							 		<input type="hidden" id="book_id" value="<?=$book['id']?>">
							 		
							 		<div class="ajax-loading"><img src="images/ajax-loader.gif"><p>Salvataggio in corso</p></div>
							 		<div class="cart_error"><p>Si è verificato un errore. Riprovare.</p></div>
							</div>  
							
						</div>
					</div>
				</div>
		
			</div>
		
		<?php
		endforeach;
		if (isset( $_GET['subject'])){
			//print_pagination($_GET['subject'], (isset($_GET['page'] ) ) ? $_GET['page']: 1 , $books['num_pages']);
		}
	}
	else echo "elenco vuoto";
	
	echo "</div>";
	
	
}

function insert_into_db(){
	/*
	 * Colonne: 2-> ean
	 * 			3->titolo 
	 * 			4->volume 
	 * 			5->autore 
	 * 			6->editore 
	 * 			7->materia
	 */
	
	require_once 'excel/excel_reader2.php';
	$excel = new Spreadsheet_Excel_Reader("../upload/testi.xls");
	$db = new db();
	
	$num_rows = $excel->rowcount();
	$num_cols = $excel->colcount();
	
	
	for($i = 2 ; $i< $num_rows; $i++)
	{
		$title = trim($excel->val($i,3) );
		if ( !empty($title) ) {
			$subject = $excel->val($i,7);
			$subject = explode(" ", $subject);
			$subject = $subject[0];
			$book = array( "EAN" => $excel->val($i,2),
							"title" => $excel->val($i,3),
							"volume" => $excel->val($i,4),
							"author" => $excel->val($i,5),
							"publisher" => $excel->val($i,6),
								"subject" => $subject
			
			);
			
			$db->insert_book($book);
		}
	}
}

//gestione carrello
class Cart
{
	
	function add($id,$num)
	{
		global $db;
		
		$book=$db->get_book($id);
		$book['num_copies']=$num;
		$_SESSION['cart'][] = $book;
		
	}
	
	function remove($id)
	{
		foreach($_SESSION['cart'] as $pos=>$value)
		{
			if($_SESSION['cart'][$pos]['id'] == $id   )
				{
					unset($_SESSION['cart'][$pos]);
				}

		}
	}
	
	function modify_num_copies($id,$num, $add){
		foreach($_SESSION['cart'] as $pos=>$value)
			{
				if( strcmp( $value['id'], $id ) == 0   )
					{
						if ($add) 
							return $_SESSION['cart'][$pos]['num_copies'] += $num;
						else 
							return $_SESSION['cart'][$pos]['num_copies'] = $num;
						
						
					}
	
			}
		
	}
	
	function get_all(){
		return $_SESSION['cart'];
	}
	
	function empty_cart()
	{
		$_SESSION['cart'] = null; //spesso l'unset non funziona a dovere
		unset($_SESSION['cart']);
	}	
	
	function is_empty(){
		if ( !isset($_SESSION['cart'] ) || count($_SESSION['cart']) == 0 )
			return true;
		return false;
	}
	
	function is_already_in_cart($book_id){
		if ( $this->is_empty())
			return false;
		$cart = $this->get_all();
		foreach ($cart as $book){
			if($book['id'] == $book_id)
				return true;
				
		}
		return false;
	}
}


function print_sidebar_subjects(){
		global $db;
		$subjects = $db->get_all_subjects();
		foreach ($subjects as $s):
		$subject_name = ucfirst(strtolower( substr($s, 0,15 )) ); 
		?>
		<li onclick="location.href='index.php?subject=<?=$s?>';"><span>
			<?=$subject_name?></span>
		<input type="hidden" value="<?=$s?>" />
			
		</li>
			
<?php 
		endforeach;
		
}


function download_books_cover(){
	ini_set('memory_limit', '712M');
	set_time_limit(0);
	global $db;
	$books = $db->get_all_books(FALSE , FALSE, FALSE, FALSE);
	print_r($books);
	foreach ($books as $book){
		$ean = trim($book['EAN']);
		error_log($ean);
		
		if (!empty($ean) && !$book['media']){
	  		$ch = curl_init();
			$url = "http://giotto.ibs.it/copertine/libro.aspx?e=".$ean."&f=l&s=1" ;
			curl_setopt($ch, CURLOPT_URL, $url);
			$fp = fopen("upload/covers/".$ean.".jpg", 'wb');
			curl_setopt($ch, CURLOPT_FILE, $fp);
			curl_exec ($ch);
			curl_close ($ch);
			fclose($fp);
			$size = getimagesize("upload/covers/".$ean.".jpg");
			if ( $size[0] == 117 && $size[1] == 170)
				unlink("upload/covers/".$ean.".jpg");
			else{
				$db->set_media($book['id'], TRUE);
			}
				
		}
	}
}


function the_cover($id , $ean){
	global $db;
	if ( $db->has_cover($id))
		echo "upload/covers/$ean.jpg";
	else echo "upload/no-cover.jpg";
	
}

function get_html_email(array $vars) {
  extract($vars);

  ob_start();
  include 'email.html.php';
  return ob_get_clean();
}

function login($email, $password){
	global $db;
	$email = strip_tags(trim($email));
	$password = trim($password);
	
	$result = $db->query("SELECT * FROM admins WHERE `email`  = '$email' AND `password` = '$password' ;") ;
	
	if ( $result ){
		$_SESSION['admin'] = true;
		$_SESSION['admin_id'] = $result['id'];
		$_SESSION['admin_email'] = $result['email'];
		return  true;
	}
	else{ 
		return false;
	}
		 
}

function check_admin(){
	if (! $_SESSION['admin'] )
		header("location: login.php");
}

function print_pagination($subject, $curr_page , $num_pages){
	
	$pagination =
	"<ul class='pagination'>
		<li class='prev'><</li>
	
		<li class=''>
			<form action='' id = 'pagination-form' onsubmit='return false;'>
				Pagina <input class='positive-integer' name='page_form' id='page_form_num' type='text' value='$curr_page'/> di $num_pages 
				<input type='hidden' id='hidden-current-page' value='$curr_page'>
				<input type='hidden' id='hidden-subject' value='$subject'>
				<input type='hidden' id='hidden-total-pages' value='$num_pages'>
				
			</form>
		</li>
		<li class='next'>></li>
	</ul>";
	/*
	$pagination="<ul class='pagination'>";
		for ( $i=1 ; $i != $num_pages ; $i++){
			if ($curr_page == $i)
				$current = "current-page";
			else
				$current = "";
			$pagination.= "<li class='page pagination_$i $current' onclick='change_page($i, \"$subject\");'> $i</li>";
		}
		$pagination.= "</ul>";*/
		echo $pagination;
}


function send_request($request){
	global $db;
	
	$is_admin = FALSE;
	ob_start();
	include("email.html.php");
	$message_user = ob_get_clean();
	
	$is_admin = TRUE;
	ob_start();
	include("email.html.php");
	$message_admin = ob_get_clean();
	
	
	$to_user = $request['email'];
	error_log($to_user);
	$to_admin = site_email();
    $from = "noreply@mercatinoscolastico.it"; 
    $subject_user = "Conferma del tuo ordine su mercatinoscolastico.it"; 
	$subject_admin = "E' stato inviato un nuovo ordine su mercatinoscolastico.it!";
     
    
    $headers  = "From: $from\r\n"; 
    $headers .= "Content-type: text/html\r\n"; 
	
    
    mail($to_user, $subject_user, $message_user, $headers) ;
    mail($to_admin, $subject_admin, $message_admin, $headers); 
    
}


function site_url(){
	$db = new db();
	$result = $db->query("SELECT value FROM options WHERE option_name = 'site_url'");
	return $result[0];
}

function site_email(){
	$db = new db();
	$result = $db->query("SELECT value FROM options WHERE option_name = 'email'");
	return $result[0];
}

?>